package com.grzx.domain.service;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grzx.domain.model.EnterpriseThirdAccount;
import com.grzx.domain.model.Question;
import com.grzx.domain.model.Reply;
import com.grzx.protocol.message.util.ResponseUtils;

/**
 * 回复信息管理service
 * 
 * @author chenwentao
 * 
 */
@Service("replyService")
@Transactional
public class ReplyService extends AbstractService {

	@Inject
	private EnterpriseThirdAccountService thirdAccountService;

	/**
	 * 根据微信用户发送请求的文本信息，返回reply
	 * 
	 * @param 请求的文本内容
	 * 
	 * @return 有对应Question那么直接返回Reply，没有则返回Null
	 */
	public Reply getReplyByContent(String content, String shopWeixinId,
			String userId) {
		shopWeixinId = shopWeixinId.trim();
		EnterpriseThirdAccount thirdAccount = thirdAccountService
				.findByYsId(shopWeixinId);
		// 根据eaId和content定位Question
		Question question = this.findUnique(
				"from Question q where q.content=? and q.ea_id=?", content,
				thirdAccount.getEa_id());
		// 如果请求无法和问题进行对应返回Null;
		if (question == null) {
			return null;
		}

		Reply reply = this.findUnique("from Reply r where r.id=?",
				question.getRely_id());
		// 注意:替换url中包含的用户id和企业微信id
		String afterDoContent = ResponseUtils.repleacShopIdAndUserId(
				reply.getContent() != null ? reply.getContent() : "", userId,
				shopWeixinId);
		reply.setContent(afterDoContent);

		return reply;
	}

	/**
	 * 根据微信用户点击的click类型的Button，返回reply
	 * 
	 * @param EventKey
	 * 
	 * @return 有对应Reply那么直接返回Reply，没有则返回Null
	 */
	public Reply getReplyById(Long Id) {
		Reply reply = this.findUnique("from Reply r where r.id=?", Id);
		if (reply == null) {
			return null;
		}
		return reply;
	}

	/**
	 * 根据ea_id查询关注微信公众号的回复,type=4
	 * 
	 * @param ea_id
	 * 
	 * @return 有对应Reply那么直接返回Reply，没有则返回Null
	 */
	public Reply getReplyByEaIdAndType(Long ea_id) {
		Reply reply = this.findUnique(
				"from Reply r where r.ea_id=? and r.type=4", ea_id);
		if (reply == null) {
			return null;
		}
		return reply;
	}

}
